package cn.springbook.common.core.config;

import cn.springbook.common.core.config.convert.DateConvert;
import cn.springbook.common.core.config.convert.LocalDateConvert;
import cn.springbook.common.core.config.convert.LocalDateTimeConvert;
import cn.springbook.common.core.config.convert.LocalTimeConvert;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
　* @description: WebMvcConfig全局公共配置
　* @param
　* @return  
　* @throws
　* @author caifenglin
　* @date 2021/7/2 17:29 
　*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 添加自定义的Converters和Formatters.
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        // @RequestBody来接收参数，这时候springboot会使用MappingJackson2HttpMessageConverter来格式化时间,此方式无效
        registry.addConverter(new DateConvert());
        registry.addConverter(new LocalDateConvert());
        registry.addConverter(new LocalTimeConvert());
        registry.addConverter(new LocalDateTimeConvert());
    }

    /**
     * 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        /**
         * 可跨域全局配置
         */
//        registry.addMapping("/**")
//                .allowedOrigins("*")
//                .allowCredentials(true)
//                .allowedMethods("GET", "POST", "DELETE", "PUT")
//                .allowedHeaders(SystemConstant.TOKEN)
//                .maxAge(3600 * 24);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/swagger-ui/")
                .setViewName("forward:/swagger-ui/index.html");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                .resourceChain(false);
    }

}